package com.lx.boot.web.config;

import com.lx.annotation.Note;
import com.lx.boot.OS;
import com.lx.boot.web.annotation.Auth;
import com.lx.util.LX;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import static com.lx.constant.DefaultBaseConstant.AUTHORIZATION;
import static com.lx.constant.DefaultBaseConstant.DEFAULT_SERVER_EXCLUDE_URL;


@Data
@Note("请求信息")
public class RequestInfo {
    @Note("接口注解")
    private Auth auth;

    @Note("接口系统配置")
    private WebProperties webProperties;

    @Note("接口请求信息")
    private HttpServletRequest request;

    @Note("接口返回信息")
    private HttpServletResponse response;

    @Note("接口ip")
    private String ip;

    @Note("接口地址")
    private String url;

    public RequestInfo(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.ip = OS.getIp(request);
        this.url = request.getServletPath();
    }

    @Note("获取请求头信息")
    private Map<String, String> getHeadersInfo() {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    @Note("过滤器排除的路径")
    public boolean isExcludeUrl(){
        return webProperties.isExcludeUrl(url) || (auth!= null && auth.exclude());
    }

    @Note("是否允许跨域")
    public boolean isAllowCrossdomain() {
        return auth!=null?auth.allowCrossdomain().get(webProperties.isAllowCrossdomain()) : webProperties.isAllowCrossdomain();
    }

    @Note("企业id是否必填")
    public boolean isFirmIdRequired() {
        return auth!=null?auth.firmIdRequired().get(webProperties.isFirmIdRequired()) : webProperties.isFirmIdRequired();
    }

    @Note("是否开启csrf")
    public boolean isCsrf() {
        return auth!=null?auth.csrf().get(webProperties.isCsrf()) : webProperties.isCsrf();
    }
}
